import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:shining_red_star/api/list_pictorial.dart';
import 'package:shining_red_star/utils/play.dart';
import 'package:shining_red_star/widgets/focus_manage/focus_widget.dart';

import '../model/pictorial.dart';
import '../wrappers/safe-area.dart';

class PictorialPage extends StatefulWidget {
  const PictorialPage({super.key});

  @override
  State<PictorialPage> createState() => _PictorialPageState();
}

class _PictorialPageState extends State<PictorialPage> {
  SwiperController controller = SwiperController();
  FocusNode focusNode = FocusNode();
  List<PictorialInfo> dataList = [];
  Timer? timer;
  int currentIndex = 0;
  AudioPlayManager audPlayer = AudioPlayManager();

  void play(int currentIndex) {
    if (dataList.length <= 1 ||
        currentIndex < 0 ||
        currentIndex >= dataList.length) {
      return;
    }
    String? aud = dataList[currentIndex].aud;
    if (aud == null) {
      return;
    }
    timer?.cancel();
    audPlayer.mediaPlay(aud).then((state) {
      if (state != PlayResult.cancel) {
        nextPlan(currentIndex);
      }
    }).catchError((err) {
      nextPlan(currentIndex);
    });
  }

  void nextPlan(int currentIndex) {
    if (dataList.length <= 1 ||
        currentIndex < 0 ||
        currentIndex >= dataList.length) {
      return;
    }
    timer?.cancel();
    int delay = dataList[currentIndex].delay ?? 5000;
    timer = Timer(Duration(milliseconds: delay), () {
      controller.next();
    });
  }

  void loadData() async {
    final List<PictorialInfo> res = await listPictorial();
    setState(() {
      dataList = res;
      nextPlan(0);
    });
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  void dispose() {
    audPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        onPopInvokedWithResult: (didPop, result) {
          audPlayer.release();
        },
        child: SafeAreaPageWrapper(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/img/background.jpg'),
                fit: BoxFit.cover,
              ),
            ),
            child: FocusWidget(
              focusNode: focusNode,
              autofocus: true,
              onFocusChange: (value) {
                setState(() {});
              },
              onKeyEvent: (node, event) {
                if (event is KeyDownEvent) {
                  switch (event.logicalKey) {
                    case LogicalKeyboardKey.arrowLeft:
                    case LogicalKeyboardKey.arrowRight:
                    case LogicalKeyboardKey.arrowUp:
                    case LogicalKeyboardKey.arrowDown:
                      if (event.logicalKey == LogicalKeyboardKey.arrowLeft ||
                          event.logicalKey == LogicalKeyboardKey.arrowUp) {
                        controller.previous();
                      } else {
                        controller.next();
                      }
                      return KeyEventResult.handled;
                    case LogicalKeyboardKey.enter:
                    case LogicalKeyboardKey.select:
                      play(currentIndex);
                      return KeyEventResult.handled;
                  }
                }
                return KeyEventResult.ignored;
              },
              child: Center(
                child: dataList.isNotEmpty
                    ? Swiper(
                        loop: true,
                        index: currentIndex,
                        itemCount: dataList.length,
                        controller: controller,
                        scrollDirection: Axis.vertical,
                        onTap: (index) {
                          play(index);
                        },
                        itemBuilder: (BuildContext context, int index) {
                          final PictorialInfo item = dataList[index];
                          final List<Widget> widgetList = [];
                          final String? img = item.img;
                          final String? title = item.title;
                          final String? subTitle = item.subTitle;
                          final String? content = item.content;
                          final String? description = item.description;

                          if (img != null) {
                            widgetList.add(Column(
                              children: [
                                Expanded(
                                    child: img.startsWith('http')
                                        ? Image.network(img,
                                            fit: BoxFit.contain)
                                        : Image.asset(img.replaceFirst('/', ''),
                                            fit: BoxFit.contain))
                              ],
                            ));
                          }
                          final bool hasImg = img != null;
                          final List<Widget> infoList = [];

                          if (title != null) {
                            title.split('\n').forEach((chunk) {
                              infoList.add(
                                Text(
                                  chunk,
                                  textAlign: hasImg
                                      ? TextAlign.left
                                      : TextAlign.center,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white,
                                    height: 1.7,
                                    fontSize: 28,
                                  ),
                                ),
                              );
                            });
                          }
                          if (subTitle != null) {
                            subTitle.split('\n').forEach((chunk) {
                              infoList.add(
                                Text(
                                  chunk,
                                  textAlign: hasImg
                                      ? TextAlign.left
                                      : TextAlign.center,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    height: 1.5,
                                    fontSize: 18,
                                  ),
                                ),
                              );
                            });
                          }
                          if (content != null) {
                            content.split('\n').forEach((chunk) {
                              infoList.add(
                                Text(
                                  chunk,
                                  textAlign: hasImg
                                      ? TextAlign.left
                                      : TextAlign.center,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    height: 1.2,
                                    fontSize: 22,
                                  ),
                                ),
                              );
                            });
                          }
                          if (description != null) {
                            infoList.add(Container(
                              margin: const EdgeInsets.only(top: 10),
                              child: Row(children: [
                                Expanded(
                                    child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: description
                                      .split('\n')
                                      .map((chunk) => Align(
                                          widthFactor: 1.0,
                                          child: Container(
                                            margin: const EdgeInsets.symmetric(
                                                vertical: 3),
                                            child: Text(
                                              chunk,
                                              style: const TextStyle(
                                                color: Colors.white,
                                                height: 1.2,
                                                fontSize: 18,
                                              ),
                                            ),
                                          )))
                                      .toList(),
                                ))
                              ]),
                            ));
                          }

                          if (infoList.isNotEmpty) {
                            if (hasImg) {
                              widgetList.add(Positioned(
                                  left: 0,
                                  right: 0,
                                  bottom: 0,
                                  child: Container(
                                    padding: const EdgeInsets.all(12),
                                    decoration: const BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment.bottomCenter,
                                        end: Alignment.topCenter,
                                        colors: [
                                          Color(0xa6000000),
                                          Colors.transparent,
                                        ],
                                      ),
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: infoList,
                                    ),
                                  )));
                            } else {
                              widgetList.add(
                                LayoutBuilder(
                                  builder: (BuildContext context,
                                      BoxConstraints constraints) {
                                    double marginHeight =
                                        constraints.maxHeight * 0.2;
                                    return Container(
                                      margin:
                                          EdgeInsets.only(top: marginHeight),
                                      padding: const EdgeInsets.all(12),
                                      constraints: const BoxConstraints(
                                        maxWidth: 480,
                                      ),
                                      child: Column(
                                        children: infoList,
                                      ),
                                    );
                                  },
                                ),
                              );
                            }
                          }

                          return Column(
                            children: [
                              Expanded(
                                child: Stack(
                                  alignment: AlignmentDirectional.center,
                                  children: widgetList,
                                ),
                              )
                            ],
                          );
                        },
                        onIndexChanged: (index) {
                          currentIndex = index;
                          audPlayer.release();
                          nextPlan(index);
                        },
                      )
                    : null,
              ),
            )));
  }
}
